<template>
  <div class="workspace-layout" :class="{ 'dark-mode': isDarkMode }">
    <!-- 顶部栏 -->
    <header class="workspace-header">
      <div class="header-left">
        <div class="logo-container">
          <img src="@/assets/logo.png" alt="Logo" class="logo" />
          <span class="app-name">ERP系统 - 工作台</span>
        </div>
      </div>

      <div class="header-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索功能、订单、商品... (Ctrl+/)"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div class="header-right">
        <el-tooltip content="快捷操作 (Ctrl+K)">
          <el-button circle @click="toggleCommandPanel">
            <el-icon><Operation /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 消息通知 -->
        <NotificationCenter />
        <el-tooltip content="导航设置">
          <el-button circle @click="showNavigationSettings">
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-tooltip>
        <el-dropdown @command="handleUserCommand">
          <div class="user-info">
            <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主要内容 -->
    <div class="workspace-container">
      <!-- 工作台首页 - 只在根路径显示 -->
      <div v-if="isWorkspaceHome" class="workspace-content">
        <!-- 常用功能 -->
        <div class="workspace-section">
          <div class="section-header">
            <h3>
              <el-icon><Star /></el-icon>
              常用功能
            </h3>
            <el-button text @click="showCustomizeDialog = true">
              <el-icon><Edit /></el-icon>
              自定义
            </el-button>
          </div>
          <div class="function-grid">
            <div
              v-for="item in favoriteItems"
              :key="item.path"
              class="function-card"
              @click="navigateTo(item.path)"
            >
              <div class="card-icon" :style="{ background: item.color }">
                <el-icon :size="28"><component :is="item.icon" /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-desc">{{ item.description }}</div>
              </div>
              <el-button
                class="remove-favorite"
                circle
                size="small"
                text
                @click.stop="removeFavorite(item.path)"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <div class="function-card add-card" @click="showCustomizeDialog = true">
              <el-icon :size="40" color="#909399"><Plus /></el-icon>
              <span>添加常用功能</span>
            </div>
          </div>
        </div>

        <!-- 功能模块 -->
        <div class="workspace-section">
          <div class="section-header">
            <h3>
              <el-icon><Grid /></el-icon>
              功能模块
            </h3>
          </div>
          <el-tabs v-model="activeModuleTab" class="module-tabs">
            <el-tab-pane label="全部" name="all">
              <div class="module-grid">
                <div
                  v-for="module in allModules"
                  :key="module.path"
                  class="module-card"
                  @click="expandModule(module)"
                >
                  <div class="module-icon" :style="{ background: module.color }">
                    <el-icon :size="32"><component :is="module.icon" /></el-icon>
                  </div>
                  <div class="module-info">
                    <div class="module-title">{{ module.title }}</div>
                    <div class="module-desc">{{ module.description }}</div>
                    <div class="module-count">{{ module.children?.length || 0 }} 个功能</div>
                  </div>
                  <el-icon class="module-arrow"><ArrowRight /></el-icon>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="销售" name="sales" />
            <el-tab-pane label="采购" name="purchase" />
            <el-tab-pane label="库存" name="inventory" />
            <el-tab-pane label="财务" name="finance" />
            <el-tab-pane label="报表" name="reports" />
          </el-tabs>
        </div>

        <!-- 快捷数据 -->
        <div class="workspace-section">
          <div class="section-header">
            <h3>
              <el-icon><DataAnalysis /></el-icon>
              数据概览
            </h3>
            <el-button text @click="navigateTo('/dashboard')">
              查看更多
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" v-for="stat in quickStats" :key="stat.id">
              <el-card class="stat-card" :class="stat.type">
                <div class="stat-content">
                  <div class="stat-icon">
                    <el-icon :size="24"><component :is="stat.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-label">{{ stat.label }}</div>
                    <div class="stat-value">{{ stat.value }}</div>
                    <div class="stat-trend" :class="stat.trend > 0 ? 'positive' : 'negative'">
                      <el-icon><component :is="stat.trend > 0 ? 'CaretTop' : 'CaretBottom'" /></el-icon>
                      {{ Math.abs(stat.trend) }}%
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 最近访问 -->
        <div class="workspace-section">
          <div class="section-header">
            <h3>
              <el-icon><Clock /></el-icon>
              最近访问
            </h3>
            <el-button text @click="clearHistory">
              清空记录
            </el-button>
          </div>
          <div class="recent-list">
            <div
              v-for="item in recentVisited"
              :key="item.path"
              class="recent-item"
              @click="navigateTo(item.path)"
            >
              <div class="recent-icon">
                <el-icon><component :is="item.icon" /></el-icon>
              </div>
              <div class="recent-info">
                <div class="recent-title">{{ item.title }}</div>
                <div class="recent-time">{{ item.time }}</div>
              </div>
              <el-icon class="recent-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 页面视图 - 非工作台首页时显示 -->
      <div v-else class="page-view">
        <!-- 返回工作台按钮 -->
        <div class="back-to-workspace">
          <el-button type="primary" @click="backToWorkspace" circle>
            <el-icon><HomeFilled /></el-icon>
          </el-button>
        </div>
        
        <div class="page-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <keep-alive :include="cachedViews">
                <component :is="Component" :key="$route.fullPath" />
              </keep-alive>
            </transition>
          </router-view>
        </div>
      </div>
    </div>

    <!-- 自定义对话框 -->
    <el-dialog
      v-model="showCustomizeDialog"
      title="自定义常用功能"
      width="800px"
    >
      <div class="customize-content">
        <el-checkbox-group v-model="selectedFunctions">
          <div class="customize-grid">
            <el-checkbox
              v-for="item in allFunctions"
              :key="item.path"
              :label="item.path"
              class="customize-item"
            >
              <div class="customize-card">
                <el-icon :size="24"><component :is="item.icon" /></el-icon>
                <span>{{ item.title }}</span>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="showCustomizeDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCustomize">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import { menuData } from '@/config/menu'
import NotificationCenter from '@/components/common/NotificationCenter.vue'

const route = useRoute()
const router = useRouter()
const navigationStore = useNavigationStore()

// 响应式数据
const searchKeyword = ref('')
const activeModuleTab = ref('all')
const showCustomizeDialog = ref(false)
const selectedFunctions = ref([])

// Store数据
const isDarkMode = computed(() => navigationStore.settings.darkMode)
const favoriteMenus = computed(() => navigationStore.favoriteMenus)

// 判断是否在工作台首页
const isWorkspaceHome = computed(() => {
  return route.path === '/' || route.path === '/workspace' || route.path === '/dashboard'
})

// 常用功能
const favoriteItems = ref([
  {
    path: '/sales/cashier',
    title: '收银台',
    description: '快速销售结算',
    icon: 'ShoppingCart',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    path: '/sales/orders',
    title: '销售订单',
    description: '订单管理',
    icon: 'Document',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
  },
  {
    path: '/inventory/products',
    title: '商品管理',
    description: '商品信息维护',
    icon: 'Box',
    color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
  },
  {
    path: '/inventory/stock',
    title: '库存管理',
    description: '库存查询调整',
    icon: 'Coin',
    color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)'
  }
])

// 所有模块
const allModules = ref(menuData.map(item => ({
  ...item,
  description: `${item.children?.length || 0}个功能模块`,
  color: getRandomGradient()
})))

// 所有功能
const allFunctions = computed(() => {
  const functions = []
  menuData.forEach(module => {
    if (module.children) {
      module.children.forEach(child => {
        if (child.children) {
          child.children.forEach(func => {
            functions.push({
              ...func,
              module: module.title,
              parent: child.title
            })
          })
        } else {
          functions.push({
            ...child,
            module: module.title
          })
        }
      })
    }
  })
  return functions
})

// 快捷数据
const quickStats = ref([
  { id: 1, label: '今日销售额', value: '¥125,680', icon: 'Money', type: 'primary', trend: 12.5 },
  { id: 2, label: '今日订单', value: '356', icon: 'Document', type: 'success', trend: 8.3 },
  { id: 3, label: '库存预警', value: '23', icon: 'Warning', type: 'warning', trend: -5.2 },
  { id: 4, label: '待处理', value: '15', icon: 'Clock', type: 'danger', trend: -2.1 }
])

// 最近访问
const recentVisited = ref([
  { path: '/sales/orders', title: '销售订单', icon: 'Document', time: '5分钟前' },
  { path: '/inventory/products', title: '商品管理', icon: 'Box', time: '1小时前' },
  { path: '/purchase/orders', title: '采购订单', icon: 'ShoppingBag', time: '3小时前' },
  { path: '/finance/accounts', title: '财务账户', icon: 'Money', time: '昨天' }
])

// 缓存的视图
const cachedViews = ref([])

// 方法
function getRandomGradient() {
  const gradients = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    'linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%)'
  ]
  return gradients[Math.floor(Math.random() * gradients.length)]
}

const handleSearch = () => {
  console.log('Search:', searchKeyword.value)
}

const toggleCommandPanel = () => {
  navigationStore.toggleCommandPanel()
}

const showNavigationSettings = () => {
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  } else if (command === 'profile') {
    router.push('/system/user-settings')
  } else if (command === 'settings') {
    router.push('/system/settings')
  }
}

const navigateTo = (path) => {
  router.push(path)
}

const expandModule = (module) => {
  // 导航到模块的第一个子功能
  if (module.children && module.children.length > 0) {
    const firstChild = module.children[0]
    if (firstChild.children && firstChild.children.length > 0) {
      router.push(firstChild.children[0].path)
    } else {
      router.push(firstChild.path)
    }
  } else {
    router.push(module.path)
  }
}

const backToWorkspace = () => {
  router.push('/dashboard')
}

const removeFavorite = (path) => {
  navigationStore.removeFavorite(path)
  favoriteItems.value = favoriteItems.value.filter(item => item.path !== path)
}

const addToFavorite = (func) => {
  navigationStore.addFavorite(func)
  if (!favoriteItems.value.find(item => item.path === func.path)) {
    favoriteItems.value.push({
      ...func,
      color: getRandomGradient()
    })
  }
}

const clearHistory = () => {
  recentVisited.value = []
}

const saveCustomize = () => {
  const selected = allFunctions.value.filter(f => selectedFunctions.value.includes(f.path))
  favoriteItems.value = selected.map(item => ({
    ...item,
    color: getRandomGradient()
  }))
  selected.forEach(item => navigationStore.addFavorite(item))
  showCustomizeDialog.value = false
}

// 生命周期
onMounted(() => {
  navigationStore.loadFromServer()
  // 初始化选中的功能
  selectedFunctions.value = favoriteItems.value.map(item => item.path)
})
</script>

<style scoped>
.workspace-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
}

.workspace-header {
  height: 64px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-left {
  flex: 0 0 auto;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  height: 40px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.header-center {
  flex: 1;
  max-width: 600px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-badge {
  display: flex;
}

.user-info {
  cursor: pointer;
}

.workspace-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  height: 0; /* 触发flex子元素的overflow */
}

.workspace-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.workspace-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.function-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.function-card {
  position: relative;
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.function-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-desc {
  font-size: 13px;
  color: #909399;
}

.remove-favorite {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.function-card:hover .remove-favorite {
  opacity: 1;
}

.add-card {
  flex-direction: column;
  justify-content: center;
  border: 2px dashed #dcdfe6;
  background: #fafafa;
}

.add-card:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.add-card span {
  margin-top: 12px;
  color: #909399;
  font-size: 14px;
}

.module-tabs {
  margin-top: 20px;
}

.module-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.module-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.module-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.module-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.module-info {
  flex: 1;
}

.module-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.module-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.module-count {
  font-size: 12px;
  color: #909399;
}

.module-arrow {
  font-size: 20px;
  color: #c0c4cc;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.stat-card.primary { border-left: 4px solid #409eff; }
.stat-card.success { border-left: 4px solid #67c23a; }
.stat-card.warning { border-left: 4px solid #e6a23c; }
.stat-card.danger { border-left: 4px solid #f56c6c; }

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #409eff;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.stat-trend.positive { color: #67c23a; }
.stat-trend.negative { color: #f56c6c; }

.recent-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s ease;
}

.recent-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.recent-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
}

.recent-info {
  flex: 1;
}

.recent-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.recent-time {
  font-size: 12px;
  color: #909399;
}

.recent-arrow {
  color: #c0c4cc;
}

.module-detail {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.detail-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.function-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.function-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.function-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.function-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.function-info {
  flex: 1;
}

.function-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.function-desc {
  font-size: 13px;
  color: #909399;
}

.page-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.back-to-workspace {
  position: fixed;
  bottom: 32px;
  right: 32px;
  z-index: 999;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: translateY(100px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.page-content {
  flex: 1;
  overflow: auto;
  background: #f0f2f5;
  padding: 20px;
}

.customize-content {
  padding: 20px 0;
}

.customize-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 12px;
}

.customize-item {
  margin: 0;
}

.customize-item :deep(.el-checkbox__label) {
  width: 100%;
}

.customize-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.customize-item.is-checked .customize-card {
  border-color: #409eff;
  background: #ecf5ff;
}

.customize-card span {
  font-size: 14px;
  color: #606266;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 暗黑模式 */
.dark-mode .workspace-header {
  background: #1f1f1f;
}

.dark-mode .workspace-content,
.dark-mode .module-detail {
  background: #141414;
}

.dark-mode .function-card,
.dark-mode .module-card,
.dark-mode .stat-card,
.dark-mode .recent-item,
.dark-mode .function-item {
  background: #1f1f1f;
  color: #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-center {
    display: none;
  }
  
  .function-grid,
  .module-grid,
  .function-list {
    grid-template-columns: 1fr;
  }
  
  .recent-list {
    grid-template-columns: 1fr;
  }
}
</style>
